package com.homework.controller;

import com.alibaba.fastjson.JSON;
import com.homework.entity.ResponseResult;
import com.homework.util.OssUtils;
import com.javaweb.servlet.HelloServlet;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: XiangHu
 * @date: 2025年03月13日 14:38
 * @describe:
 */
@WebServlet("/upload")
public class FileUpLoad extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建文件上传对象
        ServletFileUpload upload = new ServletFileUpload();
        //设置文件上传大小
        upload.setFileSizeMax(10 * 1024 * 1024);
        //判断请求中是否有上传文件
        if(ServletFileUpload.isMultipartContent(req)){
            //创建文件迭代器
            try {
                FileItemIterator itemIterator = upload.getItemIterator(req);
                //遍历所有文件
                while(itemIterator.hasNext()){
                    //获得当前文件
                    FileItemStream stream = itemIterator.next();
                    //上传到OSS
                    OssUtils.upload(stream.openStream(),stream.getName());
                    //获得文件url
                    String url = OssUtils.getURL(stream.getName());
                    //发送url给前端
                    resp.getWriter().write(JSON.toJSONString(new ResponseResult(200,"OK",url)));
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
